package com.moyun.controller.system;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.moyun.common.annotation.OperLog;
import com.moyun.common.aspect.BusinessType;
import com.moyun.model.common.R;
import com.moyun.model.po.system.SysRoleMenuEntity;
import com.moyun.model.vo.system.SysRoleMenuVo;
import com.moyun.service.system.SysRoleMenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yangboxuan
 * @since 2021-07-02
 */
@Api(tags = "系统角色菜单")
@RestController
@RequestMapping("/security/sys-role-menu")
public class SysRoleMenuController {
    @Autowired
    private SysRoleMenuService sysRoleMenuEntityService;

    /**
     * @return com.moyun.common.web.JsonResult
     * @Author yangboxuan
     * @Description 更新数据
     * @Date 2021-07-02
     * @Param [sysRoleMenuEntity]
     **/
    @ApiOperation("批量更新角色拥有的菜单")
    @PostMapping(value = "/update")
    @OperLog(operModul = "系统角色菜单模块", operType = BusinessType.UPDATE, operDesc = "更新数据")
    public R update(@RequestBody SysRoleMenuVo sysRoleMenuVo) {
        // 先删除
        Integer roleId = sysRoleMenuVo.getRoleId();
        QueryWrapper<SysRoleMenuEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id", sysRoleMenuVo.getRoleId());
        this.sysRoleMenuEntityService.remove(wrapper);
        // 再更新
        ArrayList<SysRoleMenuEntity> sysRoleMenuEntities = new ArrayList<>();
        List<Integer> menuIds = sysRoleMenuVo.getMenuIds();
        for (Integer menuId : menuIds) {
            SysRoleMenuEntity sysRoleMenuEntity = new SysRoleMenuEntity();
            sysRoleMenuEntity.setRoleId(roleId);
            sysRoleMenuEntity.setMenuId(menuId);
            sysRoleMenuEntities.add(sysRoleMenuEntity);
        }
        boolean flag = this.sysRoleMenuEntityService.saveBatch(sysRoleMenuEntities);
        if (flag) {
            return R.ok();
        } else {
            return R.error();
        }
    }

}

